﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

namespace CloudClip.ExtensionMethod
{
    public static class JsonExtensions
    {
        private static JavaScriptSerializer _JavaScriptSerializer;
        public static JavaScriptSerializer CreateJavaScriptSerializer()
        {
            if (_JavaScriptSerializer == null)
            {
                _JavaScriptSerializer = new JavaScriptSerializer();
                //這個設定是字數，UniCode是2bytes，共2147483647 * 2 bytes，所以可到4G
                _JavaScriptSerializer.MaxJsonLength = 2147483647;
            }

            return _JavaScriptSerializer;
        }

        public static string ToJsonString(object value)
        {
            JavaScriptSerializer ser = CreateJavaScriptSerializer();
            string json = ser.Serialize(value);
            return json;
        }

        public static string ToJson(this object value)
        {
            return ToJsonString(value);
        }

        public static object FromJsonString(string json, Type type)
        {
            JavaScriptSerializer ser = CreateJavaScriptSerializer();

            object result = ser.GetType()
                                    .GetMethod("Deserialize")
                                    .MakeGenericMethod(type)
                                    .Invoke(ser, new object[1] { json });
            return result;
        }

        public static object FromJson(this string json, Type type)
        {
            return FromJsonString(json, type);
        }

        public static TType FromJson<TType>(this string json)
        {
            JavaScriptSerializer ser = CreateJavaScriptSerializer();
            TType result = ser.Deserialize<TType>(json);
            return result;
        }
    }
}
